package com.ruoyi.web.controller.sale.controller;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.exception.HttpResponseFailedException;
import com.ruoyi.system.keyStrategy.KeyUtils;
import com.ruoyi.system.sale.domain.Sale;
import com.ruoyi.system.sale.domain.SaleWapper;
import com.ruoyi.system.sale.service.ISaleService;
import com.ruoyi.web.controller.weather.request.WeatherRequest;
import com.ruoyi.web.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 预警controller
 *
 * @author xuezhenwei
 * @date 2024-06-16 14:25
 */
@RestController
@RequestMapping("/sale")
@Slf4j
public class SaleController {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private ISaleService iSaleService;

    @Autowired
    private KeyUtils keyUtils;

    @GetMapping("/search")
//    @Retryable(value = {HttpResponseFailedException.class} , maxAttempts = 3, backoff = @Backoff(delay = 1000l, multiplier = 2,maxDelay = 1000l))
    public AjaxResult search(@Validated WeatherRequest weatherRequest) throws HttpResponseFailedException {

        String saleInfoByKey = keyUtils.getSaleInfoByKey(weatherRequest.getLocation());
        if (!StringUtils.isBlank(saleInfoByKey))
            return AjaxResult.success(saleInfoByKey);

        String url = "https://devapi.qweather.com/v7/warning/now";
        Map map = new HashMap();
        map.put("location" , weatherRequest.getLocation());
        map.put("lang" , weatherRequest.getLang());
//        map.put("key" , "1884dba16bee49b2b137da1130cb7422");
        map.put("key" , keyUtils.get());

        String result = httpUtils.httpUtil(map, url);

        SaleWapper object = new SaleWapper();
        try {
            object = (SaleWapper) httpUtils.strToObject(result, SaleWapper.class);
        } catch (Exception e) {
            log.error("解析异常！ {}" ,e.getMessage());
        }

        if (Objects.isNull(object) || !StringUtils.equals(object.getCode() , "200")){
            throw new HttpResponseFailedException();
        }

        if (!Objects.isNull(object) && !Objects.isNull(object.getCode()) && object.getCode().equals("200")){
            ObjectMapper objectMapper = new ObjectMapper();
            List<Sale> saleList = new ArrayList<>();
            try {
                List<Sale> oldsaleList = (List<Sale>) object.getWarning();
                saleList = objectMapper.convertValue(oldsaleList, new TypeReference<List<Sale>>() {
                });
//                saleList  = objectMapper.readValue(String.valueOf(object.getWarning()), object.collectionType(objectMapper, List.class, Sale.class));
            } catch (Exception e) {
                log.error("获取预警列表异常 {}" , e.getMessage());
            }

            if (!CollectionUtils.isEmpty(saleList)){

                for (Sale sale:saleList) {
                    if (!Objects.isNull(sale)){
                        try {
                            sale.setCityId(weatherRequest.getLocation());
                            sale.setCityName(weatherRequest.getCityName());
                            iSaleService.insertSale(sale);
                        } catch (Exception e) {
                            log.error("保存预警信息出错！ {}" , e.getMessage());
                        }
                    }
                }
            }

        }
        keyUtils.setSaleInfoByKey(weatherRequest.getLocation() , result);
        return AjaxResult.success(result);
    }

//    @Recover
    public void recover(RetryException e) {
        throw new RuntimeException("请求失败，请联系管理员！");
    }

}
